package com.cyou.qb.admin.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cyou.fz173.util.JacksonUtil;
import com.cyou.nad.datastore.DataList;
import com.cyou.nad.datastore.query.JdbcPage;
import com.cyou.nad.tag.table.TransCol;
import com.cyou.nad.utils.CollectionsUtils;
import com.cyou.qb.common.domain.AssignedWinner;
import com.cyou.qb.common.domain.Award;
import com.cyou.qb.common.domain.QiangbaAdmin;
import com.cyou.qb.common.service.ActivityService;
import com.cyou.qb.common.service.AwardConfigChanceService;
import com.cyou.qb.common.service.AwardService;
import com.cyou.qb.common.service.ConfigDisService;
import com.cyou.qb.constants.CodeTransConstants;
import com.cyou.qb.constants.Constants;
import com.cyou.qb.service.UploadService;

@Controller
@RequestMapping(value = "/award")
public class AwardController extends BaseController {

	@Resource(name = "AwardServiceCacheImpl")
	private AwardService awardService;
	@Autowired
	private UploadService uploadService;
	@Resource(name = "AwardConfigChanceServiceCacheImpl")
	private AwardConfigChanceService awardConfigChance;
	@Resource(name = "ConfigDisServiceCacheImpl")
	private ConfigDisService configDisService;
	@Resource(name = "ActivityServiceCacheImpl")
	private ActivityService activityService;

	/**
	 * 奖品list
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/index")
	public String index(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			String activeId = StringUtils.trimToEmpty(request.getParameter("activeId"));
			Assert.hasText(activeId, "未获取活动id");
			Assert.isTrue(StringUtils.isNumeric(activeId), "活动id格式错误");
			JdbcPage page = awardService.pageQueryAward(activeId, getPageNo(), getPageSize(DEFAULT_PAGE_SIZE));
			int actFaceStatus = activityService.findFaceStatus(activeId);
			model.addAttribute("page", page);
			List<TransCol> trans = new ArrayList<TransCol>(2);
			trans.add(new TransCol("type", CodeTransConstants.AWARD_TYPE));
			trans.add(new TransCol("channel", CodeTransConstants.AWARD_CHANNEL));
			model.addAttribute("trans", trans);
			saveAllParameters(request);
			model.addAttribute("dataList", page.getDataList());
			model.addAttribute("activeId", activeId);
			model.addAttribute("actFaceStatus", actFaceStatus);
		} catch (Exception e) {
			log.error("展示活动出错", e);
			print(response, "error:" + e.getMessage());
		}
		return "award/awardlist";
	}

	/**
	 * 进入保存奖品页面
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/toSavePage")
	public String toSavePage(Model model, HttpServletRequest request, HttpServletResponse response) {
		String activeId = StringUtils.trimToEmpty(request.getParameter("activeId"));
		model.addAttribute("activeId", activeId);
		return "award/addaward";
	}

	/**
	 * 保存奖品
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/saveAward")
	public String saveActivity(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			String activityId = StringUtils.trimToEmpty(request.getParameter("activeId"));
			if (faceStatus == 1 || faceStatus == 4) {
				String awardName = StringUtils.trimToEmpty(request.getParameter("awardName"));
				String type = StringUtils.trimToEmpty(request.getParameter("type"));
				String minitype = StringUtils.trimToEmpty(request.getParameter("minitype"));
				String useAdd = StringUtils.trimToEmpty(request.getParameter("useAdd"));
				String memo = StringUtils.trimToEmpty(request.getParameter("memoHtml"));
				String awardImageUrl = StringUtils.trimToEmpty(request.getParameter("awardImageUrl"));
				QiangbaAdmin admin = (QiangbaAdmin) request.getSession().getAttribute("loginedUser");

				Assert.hasText(activityId, "活动id不能为空");
				Assert.hasText(awardName, "奖品名称不能为空");
				Assert.hasText(type, "奖品类型不能为空");
				Assert.hasText(minitype, "奖品分类不能为空");
				Assert.hasText(awardImageUrl, "奖品图片不能为空");
				Assert.notNull(admin, "活动添加人为空，请重新登录或联系管理员");
				Assert.isTrue(StringUtils.isNumeric(activityId), "活动id格式错误");
				int adminId = admin.getAdminId();
				awardService.saveOneAward(awardName, type, minitype, useAdd, memo, awardImageUrl, adminId, activityId);
				print(response, "1");
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
			return "redirect:/award/index.do?activeId=" + activityId;
		} catch (Exception e) {
			e.printStackTrace();
			log.error("添加活动出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * 进入修改页面
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/toUpdatePage")
	public String toUpdatePage(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			String activeId = StringUtils.trimToEmpty(request.getParameter("activeId"));
			if (faceStatus == 1 || faceStatus == 4) {
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
				Assert.isTrue(StringUtils.isNumeric(awardId), "获取id错误");
				Award award = awardService.findAward(Integer.valueOf(awardId));
				if (award != null) {
					model.addAttribute(award);
				}
				model.addAttribute("activeId", activeId);
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("到活动修改页出错", e);
			print(response, "error:" + e.getMessage());
		}
		return "award/updateaward";
	}

	/**
	 * 修改奖品
	 */
	@RequestMapping(value = "/updateAward")
	public String updateAdmin(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String activityId = StringUtils.trimToEmpty(request.getParameter("activeId"));
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardID"));
				String awardName = StringUtils.trimToEmpty(request.getParameter("awardName"));
				String type = StringUtils.trimToEmpty(request.getParameter("type"));
				String minitype = StringUtils.trimToEmpty(request.getParameter("minitype"));
				String useAdd = StringUtils.trimToEmpty(request.getParameter("useAdd"));
				String memo = StringUtils.trimToEmpty(request.getParameter("memoHtml"));
				String awardImageUrl = StringUtils.trimToEmpty(request.getParameter("awardImageUrl"));
				QiangbaAdmin admin = (QiangbaAdmin) request.getSession().getAttribute("loginedUser");

				Assert.hasText(awardName, "奖品名称不能为空");
				Assert.hasText(type, "奖品类型不能为空");
				Assert.hasText(minitype, "奖品分类不能为空");
				Assert.hasText(awardImageUrl, "奖品图片不能为空");
				Assert.notNull(admin, "活动添加人为空，请重新登录或联系管理员");
				Assert.isTrue(StringUtils.isNumeric(awardId), "获取id错误");
				int adminId = admin.getAdminId();
				awardService.updateOnewAward(awardId, awardName, type, minitype, useAdd, memo, awardImageUrl, adminId);
				print(response, "1");
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
			return "redirect:/award/index.do?activeId=" + activityId;

		} catch (Exception e) {
			log.error("修改活动出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}

	}

	/**
	 * 删除奖品
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/removeAward")
	public String removeAward(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));

				Assert.isTrue(StringUtils.isNumeric(awardId), "获取id错误");
				awardService.removeAward(awardId);
				print(response, "1");
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("删除奖品出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * ajax 获取可用gb
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxGetSurplusGb")
	public String ajaxGetSurplusGb(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			String awardId = request.getParameter("awardId");
			int surplusGb = awardService.findSurplusGb(awardId);
			print(response, String.valueOf(surplusGb));
		} catch (Exception e) {
			log.error("获取可用Gb出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * ajax 实物入库
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxStoreEntity")
	public String ajaxStoreEntity(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
				String awardNum = StringUtils.trimToEmpty(request.getParameter("awardNum"));
				Assert.hasText(awardId, "未获取到奖品id");
				Assert.isTrue(StringUtils.isNumeric(awardId), "奖品id格式错误");
				Assert.hasText(awardNum, "未获取到奖品个数");
				Assert.isTrue(StringUtils.isNumeric(awardNum), "奖品个数格式错误");
				saveAllParameters(request);
				awardService.updateStoreEntity(awardId, awardNum);
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}

		} catch (Exception e) {
			log.error("实物奖品入库出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * ajax 经验值入库
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxStoreExperience")
	public String ajaxStoreExperience(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
				String experienceNum = StringUtils.trimToEmpty(request.getParameter("experienceNum"));
				String experienceAmount = StringUtils.trimToEmpty(request.getParameter("experienceAmount"));

				Assert.hasText(awardId, "为获取到奖品id");
				Assert.hasText(experienceNum, "未获取到奖品数量");
				Assert.hasText(experienceAmount, "未获取到每个奖品所含经验数");
				Assert.isTrue(StringUtils.isNumeric(awardId), "奖品id格式错误");
				Assert.isTrue(StringUtils.isNumeric(experienceNum), "奖品数量格式错误");
				Assert.isTrue(StringUtils.isNumeric(experienceAmount), "奖品经验数格式错误");

				awardService.updateStoreExperience(awardId, experienceNum, experienceAmount);
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}

		} catch (Exception e) {
			log.error("经验入库出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * ajax 入库GB
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxStoreGb")
	public String ajaxStoreGb(Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
				String gbnum = StringUtils.trimToEmpty(request.getParameter("gbnum"));
				String gbAmount = StringUtils.trimToEmpty(request.getParameter("gbAmount"));

				Assert.hasText(awardId, "为获取到奖品id");
				Assert.hasText(gbnum, "未获取到奖品数量");
				Assert.hasText(gbAmount, "未获取到每个奖品所含G币数");
				Assert.isTrue(StringUtils.isNumeric(awardId), "奖品id格式错误");
				Assert.isTrue(StringUtils.isNumeric(gbnum), "奖品数量格式错误");
				Assert.isTrue(StringUtils.isNumeric(gbAmount), "奖品G币格式错误");

				awardService.updateStoreGb(awardId, gbnum, gbAmount);
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}

		} catch (Exception e) {
			log.error("g币入库出错", e);
			print(response, "error:" + e.getMessage());
		}
		return null;
	}

	/**
	 * ajax 上传TXT
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxUploadTXT")
	public String ajaxUploadTXT(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {

		MultipartHttpServletRequest Multirequest = (MultipartHttpServletRequest) request;
		MultipartFile awardTxt = (MultipartFile) Multirequest.getFile("virtualTxt");
		String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
		if (awardTxt != null) {
			if (awardTxt.getBytes().length > Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX)) {
				throw new RuntimeException("文件大小不能超过"+Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX) / 1024+"kb");
			}
			try {
				int faceStatus = getFaceStatus(request, model, activityService, "activeId");
				if (faceStatus == 1 || faceStatus == 4) {
					byte awardTxtByte[] = awardTxt.getBytes();
					String awardTxtString = new String(awardTxtByte, "gb2312");

					if (!awardTxtString.trim().equals("")) {
						String txtArray[] = awardTxtString.split("\r\n");
						awardService.saveAwardDetails(txtArray, awardId);
					}

					return null;
				} else {
					throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("上传出错", e);
				print(response, "error:" + e.getMessage());
			}
		} else {
			print(response, "error: 未获取到文件");
		}
		return null;
	}

	/**
	 * ajax 追加奖品： 除虚拟奖品外,虚拟奖品直接调用ajaxUploadTXT即可
	 * Description
	 * @author lidongwei
	 * @throws IOException 
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxAddToAward")
	public String ajaxAddToAward(HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				//根据当前奖品的入库信息，追加数量
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
				String addToNum = StringUtils.trimToEmpty(request.getParameter("awardNum"));
				Assert.hasText(awardId, "未获取奖品Id");
				Assert.hasText(addToNum, "未获取追加数量");
				Assert.isTrue(StringUtils.isNumeric(awardId), "奖品id格式错误");
				Assert.isTrue(StringUtils.isNumeric(addToNum), "奖品数量个格式错误");

				awardService.updateAddToAward(awardId, addToNum);
				return null;
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("追加奖品出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}

	}

	/**
	 * 到中奖方式页面
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/toAwardConfigChance")
	public String toAwardConfigChance(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		//获取id，
		try {
			getFaceStatus(request, model, activityService, "activeId");
			String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
			String activeId = StringUtils.trimToEmpty(request.getParameter("activeId"));
			Assert.hasText(awardId, "未获取奖品id");
			Assert.isTrue(StringUtils.isNumeric(awardId), "奖品id格式错误");
			Award award = awardService.findAward(Integer.valueOf(awardId));
			Assert.notNull(award, "未获取到奖品");

			if (award.getWinType() == 2) {//如果是时间中奖
				List<String> timeWinList = new ArrayList<String>();
				String winTimes = award.getDateWin();
				if (winTimes != null && !winTimes.equals("")) {
					String[] winTimeArray = winTimes.split(";");
					if (winTimeArray != null && winTimeArray.length > 0) {
						for (int i = 0; i < winTimeArray.length; i++) {
							timeWinList.add(getFrontWinStr(winTimeArray[i]));
						}
					}
				}
				model.addAttribute("timeWinList", timeWinList);
			}
			//获取指定用户list
			List<AssignedWinner> assignedWinnerList = new ArrayList<AssignedWinner>();
			assignedWinnerList = awardConfigChance.findAssignedWinnerListByAwardId(awardId);
			if (assignedWinnerList != null) {
				model.addAttribute("assignedWinnerList", assignedWinnerList);
			}
			//获取尾数list
			List<Integer> numWins = awardService.findNumWinListByActId(activeId);
			model.addAttribute("numWins", numWins);
			model.addAttribute("award", award);
			return "award/awardconfigchance";

		} catch (Exception e) {
			log.error("进入配置中奖方式页面出错", e);
			print(response, "error:" + e.getMessage());
			model.addAttribute("error", e.getMessage());//用于在list中显示
			return null;
		}
	}

	/**
	 * 保存中奖方式
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/saveAwardConfigChance")
	public String saveAwardConfigChance(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
		try {

			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String activeId = StringUtils.trimToEmpty(request.getParameter("activeId"));
				String probabilityCheckBox = StringUtils.trimToEmpty(request.getParameter("probabilityCheckBox"));
				String prizeRadio = StringUtils.trimToEmpty(request.getParameter("prizeRadio"));
				String prizeTimeInput = StringUtils.trimToEmpty(request.getParameter("timeHidden"));
				prizeTimeInput = getWinStr(prizeTimeInput, awardId);
				String prizeNumInput = StringUtils.trimToEmpty(request.getParameter("prizeNumInput"));
				if ("3".equals(prizeRadio)) {
					Assert.isTrue(NumberUtils.isDigits(prizeNumInput), "尾数必须是数字");
				}
				if (prizeTimeInput.length() > 512) {
					throw new Exception("添加中奖时间个数超过57个");
				}
				Assert.hasText(awardId, "未获取奖品id");
				Assert.isTrue(StringUtils.isNumeric(awardId), "获取的奖品id格式错误");
				Assert.hasText(activeId, "未获取活动id");
				Assert.isTrue(StringUtils.isNumeric(activeId), "获取的活动id格式错误");

				awardConfigChance.saveAwardConfigChance(awardId, probabilityCheckBox, prizeRadio, prizeTimeInput,
						prizeNumInput);

				model.addAttribute("awardId", awardId);
				model.addAttribute("activeId", activeId);
				return "redirect:/award/index.do?activeId=" + activeId;
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("保存中奖方式出错", e);
			print(response, "error:" + e.getMessage());
			model.addAttribute("error", e.getMessage());//用于在list中显示
		}
		return "redirect:/award/toAwardConfigChance.do?awardId=" + awardId;

	}

	/**
	 * ajax添加指定用户
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxAddAssignWinner")
	public String ajaxAddAssignWinner(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
				String passport = StringUtils.trimToEmpty(request.getParameter("assignPassport"));
				String num = StringUtils.trimToEmpty(request.getParameter("assignNum"));
				Assert.hasText(awardId, "未获取奖品id");
				Assert.hasText(passport, "未获取指定用户Passport");
				Assert.hasText(num, "未获取指定奖品个数");
				Assert.isTrue(StringUtils.isNumeric(awardId), "获取奖品id格式错误");
				Assert.isTrue(StringUtils.isNumeric(num), "获取指定奖品个数格式错误");
				boolean hasPassport = awardConfigChance.findPassport(passport, awardId);
				Assert.isTrue(!hasPassport, "此指定用户已存在");
				AssignedWinner assignWinner = awardConfigChance.saveOneAssignWinner(awardId, passport, num);
				String assignJStr = JacksonUtil.toJson(assignWinner);
				response.getWriter().print(assignJStr);
				return null;
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}

		} catch (Exception e) {
			log.error("添加指定用户出错", e);
			print(response, "error:" + e.getMessage());
			model.addAttribute("error", e.getMessage());//用于在list中显示
			return null;
		}

	}

	/**
	 * 动态删除一个指定用户
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxDeleteOneAddAssignWinner")
	public String ajaxDeleteOneAddAssignWinner(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String assignedWinnerId = StringUtils.trimToEmpty(request.getParameter("assignedWinnerId"));
				Assert.hasText(assignedWinnerId, "未获取制定中奖用户id");
				Assert.isTrue(StringUtils.isNumeric(assignedWinnerId), "获取奖品id格式错误");
				awardConfigChance.removeOneAssignWinner(assignedWinnerId);
				return null;
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}

		} catch (Exception e) {
			log.error("删除指定用户出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}
	}

	/**
	 * 获取当前奖品剩余数量
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxGetCurrNum")
	public String ajaxGetCurrNum(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
			Assert.hasText(awardId, "未获取奖品id");
			Assert.isTrue(StringUtils.isNumeric(awardId), "获取奖品id格式错误");
			int currNum = awardService.findCurrNum(awardId);
			print(response, "" + currNum);
		} catch (Exception e) {
			log.error("获取当前剩余奖品个数出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}

		return null;
	}

	/**
	 * 到配置摇奖盘页
	 * activeId
	 * @throws IOException 
	 */
	@RequestMapping(value = "/toConfigDiscPage")
	public String toConfigDiscPage(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			//获取activeId,
			String activeId = StringUtils.trimToEmpty(request.getParameter("activeId"));
			Assert.hasText(activeId, "未获取到活动id");
			Assert.isTrue(StringUtils.isNumeric(activeId), "获取活动id格式出错");
			//根据id获取奖品信息（奖品id+奖品名称+奖品max数）
			DataList awardList = awardService.findAwardsByActId(activeId);
			model.addAttribute("awardList", awardList);
			model.addAttribute("activeId", activeId);
			return "award/awardconfigdisc";
		} catch (Exception e) {
			log.error("获取当前剩余奖品个数出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}

	}

	/**
	 * ajax保存摇奖盘
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/ajaxSaveConfigDis")
	public String ajaxSaveConfigDis(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				//获取activeID,奖品id和奖品所对应的位置
				String activeId = StringUtils.trimToEmpty(request.getParameter("activeId"));
				String positions = StringUtils.trimToEmpty(request.getParameter("positions"));

				Assert.hasText(activeId, "未获取到活动id");
				Assert.hasText(positions, "未配置摇奖盘");
				Assert.isTrue(StringUtils.isNumeric(activeId), "获取活动id格式出错");
				List<String> awIds = new ArrayList();
				List<String> pos = new ArrayList();
				//处理从前台传回的数据：
				dealWithPosition(positions, awIds, pos);
				configDisService.saveConfigDis(activeId, awIds, pos);

				return "redirect:/award/index.do?activeId=" + activeId;
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}

		} catch (Exception e) {
			log.error("配置摇奖盘出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}
	}

	/**
	 * 进入奖品明细页面
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	@RequestMapping(value = "/toAwardDetailList")
	public String toAwardDetailList(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			//初次进入获取awardId、type
			String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
			String type = StringUtils.trimToEmpty(request.getParameter("type"));
			String activeId = StringUtils.trimToEmpty(request.getParameter("activeId"));
			int actFaceStatus = activityService.findFaceStatus(activeId);
			Assert.hasText(awardId, "未获取奖品id");
			Assert.hasText(type, "未获取奖品类型");
			Assert.isTrue(StringUtils.isNumeric(awardId), "奖品id格式错误");
			Assert.isTrue(StringUtils.isNumeric(type), "奖品类型格式错误");

			JdbcPage page = null;
			if (type.equals("1")) {//实物
				String userNick = StringUtils.trimToEmpty(request.getParameter("userNick"));
				String userId = StringUtils.trimToEmpty(request.getParameter("userId"));
				page = awardService.pageQueryEntity(awardId, userNick, userId, getPageNo(),
						getPageSize(DEFAULT_PAGE_SIZE));
			} else if (type.equals("2")) {//虚拟
				String vUserNick = StringUtils.trimToEmpty(request.getParameter("vUserNick"));
				String vUserId = StringUtils.trimToEmpty(request.getParameter("vUserId"));
				String vWin = StringUtils.trimToEmpty(request.getParameter("vWin"));
				page = awardService.pageQueryVirtual(awardId, vUserNick, vUserId, vWin, getPageNo(),
						getPageSize(DEFAULT_PAGE_SIZE));
			} else if (type.equals("3") || type.equals("4")) {//经验值和G币
				String userNick = StringUtils.trimToEmpty(request.getParameter("userNick"));
				String userId = StringUtils.trimToEmpty(request.getParameter("userId"));
				page = awardService.pageQueryGBAndExp(awardId, userNick, userId, getPageNo(),
						getPageSize(DEFAULT_PAGE_SIZE));
			}
			int currNum = awardService.findCurrNum(awardId);
			model.addAttribute("page", page);
			model.addAttribute("actFaceStatus", actFaceStatus);
			model.addAttribute("type", type);
			model.addAttribute("awardId", awardId);
			model.addAttribute("activeId", activeId);
			
			model.addAttribute("cNum", currNum);
			saveAllParameters(request);
			return "award/awarddetaillist";
		} catch (Exception e) {
			log.error("获取奖品明细信息出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}

	}

	/**
	 * ajax 修改非虚拟物品的当前数量
	 * Description
	 * @author lidongwei
	 * @since 2012-10-16
	 */

	@RequestMapping(value = "/ajaxChangeNOVirtualNum")
	public String ajaxChangeNOVirtualNum(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
				String newCurrNum = StringUtils.trimToEmpty(request.getParameter("currNum"));
				Assert.hasText(awardId, "未获取奖品id");
				Assert.hasText(newCurrNum, "未获取更新的个数");
				Assert.isTrue(StringUtils.isNumeric(awardId), "获取的奖品id格式不对");
				Assert.isTrue(StringUtils.isNumeric(newCurrNum), "获取的个数格式不对");
				awardService.updateNoVirNum(awardId, newCurrNum);
				print(response, "1");
				return null;
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("修改非虚拟奖品个数出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}

	}

	/**
	 * ajax删除虚拟物品
	 * Description
	 * @author lidongwei
	 * @since 2012-10-18
	 */
	@RequestMapping(value = "/ajaxRemoveVirtual")
	public String ajaxRemoveVirtual(Model model, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		try {
			int faceStatus = getFaceStatus(request, model, activityService, "activeId");
			if (faceStatus == 1 || faceStatus == 4) {
				String[] virtualIds = request.getParameter("chks").split(",");
				String awardId = StringUtils.trimToEmpty(request.getParameter("awardId"));
				List<String> virtualIdList = CollectionsUtils.array2List(virtualIds);
				Assert.notNull(virtualIdList);
				Assert.hasText(awardId, "未获取奖品Id");
				Assert.isTrue(StringUtils.isNumeric(awardId), "获取奖品格式出错");
				for (int i = 0; i < virtualIdList.size(); i++) {
					Assert.hasText(virtualIdList.get(i), "awardId不能为空");
					Assert.isTrue(NumberUtils.isDigits(virtualIdList.get(i)), "id必须是数字");
				}
				awardService.removeVirtual(virtualIdList, awardId);
				print(response, "1");
				return null;
			} else {
				throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
			}
		} catch (Exception e) {
			log.error("删除虚拟奖品出错", e);
			print(response, "error:" + e.getMessage());
			return null;
		}
	}

	/**
	 * 
	 * Description ajax上传图片
	 * @author lidongwei
	 * @since 2012-10-6
	 */

	@RequestMapping(value = "/ajaxUpload")
	public String ajaxUpload(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		MultipartHttpServletRequest Multirequest = (MultipartHttpServletRequest) request;
		MultipartFile awardImage = (MultipartFile) Multirequest.getFile("awardImage");
		if (awardImage != null) {
			if (awardImage.getBytes().length > Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX)) {
				print(response, "error:文件大小不能超过"+Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX) / 1024+"k");
				return null;
			}
			try {
				int faceStatus = getFaceStatus(request, model, activityService, "activeId");
				if (faceStatus == 1 || faceStatus == 4) {
					String visitUrl = uploadService.uploadFile(awardImage.getBytes(), awardImage.getOriginalFilename(),
							Integer.valueOf(Constants.UPLOAD_FILE_SIZE_MAX) / 1024);
					print(response, visitUrl);
					return null;
				} else {
					throw new Exception("活动状态处于正在进行或已经结束，不能进行此操作");
				}
			} catch (Exception e) {
				e.printStackTrace();
				log.error("上传出错", e);
				print(response, "error:" + e.getMessage());
			}
		} else {
			print(response, "error: 未获取到文件");
		}

		return null;
	}

	/**
	 * 将字符串处理成前台可显示的样式 11:00 AM
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */

	private String getFrontWinStr(String winTime) {
		StringBuffer time = new StringBuffer("");
		String[] t = winTime.split(":");

		if (Integer.valueOf(t[0]) > 12) {
			t[0] = (Integer.valueOf(t[0]) - 12) + "";
			time = time.append(t[0] + ":" + t[1] + " PM");
		} else if (Integer.valueOf(t[0]) < 10) {
			t[0] = String.valueOf(t[0].charAt(1));
			time = time.append(t[0] + ":" + t[1] + " AM");
		} else {
			time = time.append(t[0] + ":" + t[1] + " AM");
		}
		return time.toString();

	}

	/**
	 * 获取页面取得的中奖时间字符串，形成可存储在数据库中的形式
	 * Description
	 * @author lidongwei
	 * @since 2012-10-15
	 */
	private String getWinStr(String winTime, String awardId) throws Exception {
		String re = "";
		if (!winTime.equals("")) {
			String[] winTimes = winTime.split(";");
			for (int i = 0; i < winTimes.length; i++) {
				String tims[] = winTimes[i].split(" ");
				if (tims != null && tims.length > 0) {
					if ("PM".equalsIgnoreCase(tims[1])) {
						String littletims[] = tims[0].split(":");
						tims[0] = (Integer.valueOf(littletims[0]) + 12) + ":" + littletims[1] + "";
					}
					tims[0] = tims[0] + ":00";
					if (tims[0].length() < 8) {//处理times位数不为两位的情况，将7:00:00变为07:00:00
						tims[0] = "0" + tims[0];
					}
					re = re + tims[0] + ";";
				}
			}

		}
		return re;
	}

	/**
	 * 
	 * Description 处理从前台传回的九宫格配置，前台传回来的字符串为："1:3,4:5,8:9" 含义为：
	 * 在第一个位置放置的是awardid为3的奖品
	 * @author lidongwei
	 * @throws Exception 
	 * @since 2012-10-13
	 */
	private void dealWithPosition(String positions, List<String> awIds, List<String> position) throws Exception {
		String[] pos = positions.split(",");
		if (pos.length >= 8) {
			throw new Exception("配置奖品位置超过7个");
		} else {
			for (int i = 0; i < pos.length; i++) {
				position.add(pos[i].split(":")[0]);
				awIds.add(pos[i].split(":")[1]);

			}
		}

	}

}
